package com.paireach.bw.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.paireach.bw.bean.Goods;
import com.paireach.bw.bean.OrdersBean;
import com.paireach.bw.event.AppEvent;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.List;

public class JsonPaser {

    private static final String TAG = "JsonPaser";

    /**
     * 解析首页返回的第一个未接单信息
     *
     * @param json
     */
    public static void parseFirstAvailableOrder(String json) {
        AppEvent event = new AppEvent();
        event.setTag("first_available_order_info");
        try {
            JSONObject object = new JSONObject(json);
            int bidcount = object.getInt("bidcount");
            event.setObj2(bidcount);
            String tmp = object.getString("loadResult");
            if (tmp.equals("0")) {
                //登录失败，没有该用户信息
                event.setCode(1);
                event.setExtraInfo("无运单!");
            } else {
                //解析用户数据
                JSONObject object1 = object.getJSONObject("orders");
                OrdersBean user = new Gson().fromJson(object1.toString(), OrdersBean.class);
                event.setCode(0);
                event.setObj1(user);
            }
        } catch (Exception e) {
            event.setCode(2);
            event.setExtraInfo("数据解析失败！");
        } finally {
            EventBus.getDefault().post(event);
        }
    }



    /**
     * 解析获取运单中的商品信息
     *
     * @param json
     */
    public static void parseOrderDetailGoods(String json) {
        AppEvent event = new AppEvent();
        event.setTag("order_detail_goods");
        try {
            JSONObject object = new JSONObject(json);
            String tmp = object.getString("loadResult");
            if (tmp.equals("0")) {
                //失败，没有信息
                event.setCode(1);
                event.setExtraInfo("无商品");
            } else {
                //解析数据
                JSONArray object1 = object.getJSONArray("orders");
                List<Goods> list = new Gson().fromJson(object1.toString(), new TypeToken<List<Goods>>() {
                }.getType());
                event.setCode(0);
                event.setObj1(list);
            }
        } catch (Exception e) {
            event.setCode(2);
            event.setExtraInfo("数据解析失败！");
        } finally {
            EventBus.getDefault().post(event);
        }
    }



}
